package com.cn.test.xuanhttplibrary.okhttp.callback;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.RequiresApi;

import android.text.TextUtils;
import android.util.Log;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.test.base.GlobalApp;
import com.cn.test.util.LogUtil;
import com.cn.test.util.ToastUtil;
import com.cn.test.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.test.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.test.xuanhttplibrary.okhttp.result.Result;


import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * @author Administrator
 * @time 2017/3/30 0:45
 * @des ${TODO}
 */

public abstract class BaseCallback<T> implements Callback {
    // private Gson mGson;
    private Class<T> mClazz;
    private Handler mDelivery;

    public BaseCallback(Class<T> clazz) {
       /* mType = getSuperclassTypeParameter(getClass());
        mGson = new Gson();*/
        mClazz = clazz;
        mDelivery = new Handler(Looper.getMainLooper());
    }

    public abstract void onResponse(ObjectResult<T> result);

    public abstract void onError(Call call, Exception e);

    @Override
    public void onFailure(Call call, IOException e) {
        Log.i(HttpUtils.TAG, "服务器请求失败", e);
        errorData(call, e);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d("debug", "返回的code代码为" + response.code());
        if (response.code() == 200) {
            try {
                ObjectResult<T> result = new ObjectResult<T>();
                String datainfo = response.body().string();
                Log.d("Debug", "请求返回的数据" + datainfo);
                //将返回的信息 转化为json对象
                JSONObject jsonObject = JSON.parseObject(datainfo);
                //返回请求接口的状态指   相当于1 0  true标识请求成功   false 标识请求失败 请求失败toast


                int code = jsonObject.getIntValue(Result.RESULT_CODE);
                if (code==1000){
                    LogUtil.i(HttpUtils.TAG, "登录过期，请重新登陆");
//                    Intent intent = new Intent(GlobalApp.getAppContext(), LoginActivity.class);
//                    // 清空activity栈，
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                    GlobalApp.getAppContext().startActivity(intent);
                    Looper.prepare();
                    ToastUtil.showShort("token过期，请重新登录");
                    Looper.loop();
                    return;
                }
                //CODE 2000 是请求成功
                if (code==2000) {
                    result.setResultCode(jsonObject.getIntValue(Result.RESULT_CODE));
                    result.setResultMsg(jsonObject.getString(Result.RESULT_MSG));
                    result.setCurrentTime(jsonObject.getLongValue(Result.RESULT_CURRENT_TIME));
                    // 需要返回数据的时候走下面的方法
                    if (!mClazz.equals(Void.class)) {
                        String data = jsonObject.getString(Result.DATA);
                        if (!TextUtils.isEmpty(data)) {
                            if (mClazz.equals(String.class) || mClazz.getSuperclass().equals(Number.class)) {// String
                                // 类型或者基本数据类型（Integer）
                                result.setData(castValue(mClazz, data));
                            } else {
                                result.setData(JSON.parseObject(data, mClazz));
                            }
                        }
                    }
                    successData(result);
                }else {
                    Looper.prepare();
                    ToastUtil.showShort(jsonObject.getString(Result.RESULT_MSG));
                    Looper.loop();
                }
            } catch (Exception e) {
//                LogUtils.log(response);
//                Reporter.post("json解析失败, ", e);
                LogUtil.i(HttpUtils.TAG, "数据解析异常:" + e.getMessage());
                errorData(call, new Exception("数据解析异常"));
            }
        } else if (response.code() == 401) {

        } else {
            LogUtil.i(HttpUtils.TAG, "服务器请求异常" + response.code());
            errorData(call, new Exception("服务器请求异常"));
        }
    }

    protected void successData(final ObjectResult<T> data) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (data.getResultCode() == 1030101 || data.getResultCode() == 1030102) {
                    // 缺少访问令牌 || 访问令牌过期或无效
                    return;
                }
                onResponse(data);
            }
        });
    }

    protected void errorData(final Call call, final Exception e) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                onError(call, e);
            }
        });
    }

    private T castValue(Class<T> clazz, String data) {
        try {
            Constructor<T> constructor = clazz.getConstructor(String.class);
            return constructor.newInstance(data);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
